<template>

  <div class="main">
    <img class="background" src="/static/images/qabg.jpg"/>

    <div class="timerbar">
      <i-progress :percent="targetPer" :status="processStatus" hide-info></i-progress>
    </div>

    <div class="questionbackground">
      <img src="/static/images/question.png" />
      <div class="question">
        {{questionList[currentIndex].content}}
      </div>
    </div>

    <div class="currentstate">
    第{{barrierLevel}}关：{{currentIndex+1}}/{{questionList.length}}
    </div>

    <div class="answer" v-for="item in questionList[currentIndex].options" :key="index">
      <button  v-if = 'questionList[currentIndex].rightAnswer === questionList[currentIndex].options[index]'
               class="answerbtn" :class="{'right':showRight}" @click="rightAction" :disabled="disabled2answer">
        {{item}}
      </button>
      <button  v-else class="answerbtn" :class="{'wrong':showWrong[index]}"
               @click="wrongAction(index)" :disabled="disabled2answer">
        {{item}}
      </button>
    </div>

    <i-modal :visible="visible" :actions="actions" @iclick="modalClick">
      <view>{{failMsg}}</view>
      <view> 是否重闯此关？</view>
    </i-modal>
    <i-modal :visible="passVisible" :actions="passActions" @iclick="passClick">
      <view>恭喜你，通关了!</view>
    </i-modal>
    <i-modal :visible="passAll" :actions="passAllActions" @iclick="passAllClick">
      <view>恭喜你，已通过所有关卡!</view>
    </i-modal>

  </div>
</template>


<script>
  import HttpKit from './http-kit'

  export default {
    data () {
      return {
        duration: 1000 * 10, // 答题时间
        answerTimeout: '', // 答题超时定时器
        interval: '', // 进度条周期刷新定时器
        processStatus: '', // 进度条状态
        targetPer: 100, //  进度条百分比
        barrierLevel: 0, // 正在闯的关卡
        disabled2answer: false, // 是否禁用答题按钮
        subject: '',
        grade: '',
        openid: '',
        questionList: [{ // 该关卡的所有问题
          id: '',
          content: '', // 题干
          options: [], // 选项
          rightAnswer: '' //  答案
        }],
        currentIndex: 0, // 当前正在答的题的索引值
        resultList: [], //  存放答题结果
        showRight: false,
        showWrong: [],
        visible: false,
        passVisible: false,
        passAll: false,
        failMsg: '',
        actions: [
          {name: '返回选关', color: '#ed3f14'},
          {name: '再闯本关', color: '#2b85e4'}
        ],
        passActions: [
          {name: '返回选关', color: '#ed3f14'},
          {name: '下一关', color: '#2b85e4'}
        ],
        passAllActions: [
          {name: '返回选关', color: '#ed3f14'},
          {name: '返回首页', color: '#2b85e4'}
        ]
      }
    },
    methods: {
      /**
       *用户答对题目，若非是最后一题，则刷新题目
       *若是最后一题，并且还有关卡可解锁，则显示下一关对话框
       *若是最后一题，没有关卡可解锁，则显示通过所有关卡对话框
       */
      rightAction () {
        // 刷新题目前第一次点击有效，后续点击直接返回
        if (this.disabled2answer) { return }
        this.disabled2answer = true
        this.processStatus = 'normal'
        this.targetPer = 100
        this.showRight = true
        this.stopTimeBar()
        this.addResult(1)
        setTimeout(() => {
          this.showRight = false
          // 刷新下一道题
          if (this.currentIndex < this.questionList.length - 1) {
            this.currentIndex++
            this.disabled2answer = false
            console.log('第' + (this.currentIndex + 1) + '题答案:', this.questionList[this.currentIndex].rightAnswer)
            this.initTimeBar()
          } else {
            // 通关，发送答题结果以更新积分
            this.pushResult(1)
          }
        }, 1000)
      },
      /**
       *用户答错题目，则显示闯关失败对话框
       */
      wrongAction (index) {
        if (this.disabled2answer) { return }
        this.disabled2answer = true
        this.failMsg = '很遗憾，你答错了'
        this.stopTimeBar()
        wx.vibrateShort()
        const temp = []
        temp[index] = true
        this.showWrong = temp
        this.addResult(0)
        // 发送答题结果
        setTimeout(() => {
          this.pushResult(0)
          this.showWrong[index] = false
        }, 1000)
      },
      /**
       *添加答题结果
       */
      addResult (isRight) {
        this.resultList[this.currentIndex] = {
          questionId: this.questionList[this.currentIndex].id,
          result: isRight
        }
      },
      /**
       *失败对话框对应选择的处理
       */
      modalClick ({mp}) {
        this.visible = false
        const index = mp.detail.index
        // console.log(index)
        if (index === 0) { // 返回选关
          wx.navigateBack({delta: 1})
        } else if (index === 1) { //  再闯本关
          this.initQuestionData()
        }
      },
      /**
       *通关对话框对应选择的处理
       */
      passClick ({mp}) {
        this.passVisible = false
        const index = mp.detail.index
        // console.log(index)
        if (index === 0) { //  返回选关
          wx.navigateBack({delta: 1})
        } else if (index === 1) { //  下一关
          this.barrierLevel++
          // 发送请求更新关卡
          this.initQuestionData()
        }
      },
      /**
       *通过所有关卡对话框对应选择的处理
       */
      passAllClick ({mp}) {
        this.passAll = false
        const index = mp.detail.index
        // console.log(index)
        if (index === 0) { //  返回选关
          wx.navigateBack({delta: 1})
        } else if (index === 1) { //  返回首页
          wx.navigateBack({delta: 2})
        }
      },
      /**
       * 初始化答题数据
       */
      initQuestionData () {
        this.stopTimeBar()
        this.targetPer = 100
        this.processStatus = 'normal'
        this.questionList = [{
          id: '',
          content: '',
          options: [],
          rightAnswer: ''
        }]
        this.currentIndex = 0
        this.resultList = []
        this.visible = false
        this.passVisible = false
        this.passAll = false
        this.disabled2answer = false
        // 发送请求获取题目数据
        HttpKit.getQuestion(this.subject, this.grade, this.barrierLevel,
          newList => {
            this.questionList = newList
            this.initTimeBar()
            console.log('\n')
            console.log('第1题答案:', this.questionList[0].rightAnswer)
          })
      },
      // 初始化倒计时进度条
      initTimeBar () {
        this.targetPer = 100
        this.processStatus = 'normal'
        this.interval = setInterval(() => {
          if (this.targetPer < 20 && this.processStatus === 'normal') {
            this.processStatus = 'wrong'
          }
          if (this.targetPer > 0) { this.targetPer -= 1 }
        }, (this.duration - 500) * 0.01)
        this.answerTimeout = setTimeout(this.timeout, this.duration)
      },
      stopTimeBar () {
        // this.targetPer = 0
        clearInterval(this.interval)
        clearTimeout(this.answerTimeout)
      },
      timeout () {
        this.failMsg = '很遗憾，你超时了'
        this.addResult(0)
        // 发送答题结果
        this.pushResult(0)
      },
      /**
       *推送答题结果
       */
      pushResult (isPass) {
        const passCallback = (highestUnlockBarrier) => {
          // 当前关卡小于已解锁的最高关卡，表明还有下一关
          if (this.barrierLevel < highestUnlockBarrier) {
            this.passVisible = true
          } else { this.passAll = true }
        }
        const failCallback = () => { this.visible = true }
        const successCallback = isPass ? passCallback : failCallback
        HttpKit.pushResult(this.openid, this.subject, this.grade,
          this.barrierLevel, this.resultList, successCallback,
          () => this.showError(isPass))
      },
      /**
       *推送答题结果失败时弹出对话框
       */
      showError (isPass) {
        const _this = this
        wx.showModal({
          title: '提示',
          content: '请检查网络！',
          confirmText: '重试',
          success (res) {
            if (res.confirm) {
              _this.pushResult(isPass)
            }
          }
        })
      }
    },
    beforeMount () {
      // 获取参数
      this.subject = wx.getStorageSync('subject')
      this.grade = wx.getStorageSync('grade')
      this.openid = wx.getStorageSync('userInfo').openid
      this.barrierLevel = this.$root.$mp.query.barrierLevel
      // this.barrierLevel = 1
      this.initQuestionData()
    },
    onUnload () {
      /**
       *未答完题强制返回
       */
      this.stopTimeBar()
      if (this.currentIndex !== this.resultList.length - 1) {
        wx.showModal({
          title: '提示',
          content: '你放弃了答题......闯关失败!',
          showCancel: false
        })
      }
    },
    onPullDownRefresh () {
      if (!this.questionList[0].id) {
        this.initQuestionData()
      }
      wx.stopPullDownRefresh()
    }
  }
</script>

<style scoped>
  .main{
    overflow: hidden;
  }
  .background{
    position: fixed;
    height: 100%;
    width: 100%;
    opacity: 0.5;
  }
  .questionbackground {
    display: flex;
    padding-top: 10px;
    align-items: center;
    flex-direction: column;
    position: relative;
    height: 100%;
    width: 100%;
    /*border:3px solid #2b85e4;*/
    /*border-radius: 10px;*/
    margin: 0 auto;
  }
  .question{
    color:white;
    overflow-y:auto;
    text-align:center;
    position:absolute;
    /*font-size: 18px;*/
    height:280rpx;
    width:497rpx;
    top:80rpx;
  }
  .answer{
    margin-top: 18px;
  }
  .answerbtn{
    width: 90%;
    border-radius: 20px;
    background-color: #F5F5F5;
  }
  .answerbtn::after{
    border: none;
  }
  .currentstate{
    position: relative;
    text-align: center;
    font-size: 20px;
    margin: 0 auto;
    color: #2b85e4;
  }
  .right{
    animation:mymove 1s;
    animation-fill-mode: forwards;
  }
  @keyframes mymove
  {
    /*from {background-color:#F5F5F5;}*/
    to {background-color:#19be6b;}
  }
  .wrong{
    animation:wrong-move 1s;
    animation-fill-mode: forwards;
  }
  @keyframes wrong-move
  {
    /*from {background-color:white;}*/
    to {background-color:red;}
  }
  .timerbar{
    width: 80%;
    margin: 0 auto;
    position: relative;
  }
</style>

